import { MarDayReport, MarkerListType } from '@/api/scada/type'
import { ref, shallowRef, unref } from 'vue'
import { copyData, copyToClipboard, download } from '@antv/s2'
import { ElTree } from 'element-plus'
import { useSCADAStore } from '@/store/modules/scada'
import SCADAApi from '@/api/scada'
function MonthGasConsumption(data: any[]) {
  const result = {}
  data.forEach((item) => {
    const dateKey = item.date // 使用日期作为分组键
    if (!result[dateKey]) {
      result[dateKey] = {
        date: dateKey,
        siteName: '总计',
        devName: ' ',
        gasConsumption: 0
      }
    }
    result[dateKey].gasConsumption += item.gasConsumption
  })
  return Object.values(result)
}
function AllMarkerMonthGas(data: any[]) {
  const result = {}
  data.forEach((item) => {
    const groupKey = `${item.devNumber}_${item.devNo}` // 使用日期作为分组键
    if (!result[groupKey]) {
      result[groupKey] = {
        date: '总计',
        devNumber: item.devNumber,
        devNo: item.devNo, // 新增 devNo 字段
        siteName: item.siteName, // 保留站点名称
        devName: item.devName, // 设备名称显示为"总计"
        gasConsumption: 0
      }
    }
    result[groupKey].gasConsumption += item.gasConsumption
  })
  return Object.values(result)
}
function DayGasConsumption(data: any[]) {
  const result = {}
  data.forEach((item) => {
    const dateKey = item.sampleTime // 使用日期作为分组键
    if (!result[dateKey]) {
      result[dateKey] = {
        siteName: '总计',
        devName: ' ',
        sampleTime: dateKey,
        sumScn: 0,
        sumWcn: 0,
        gasConsumption: 0
      }
    }
    result[dateKey].sumScn += Number(item.sumScn)
    result[dateKey].sumWcn += Number(item.sumWcn)
    result[dateKey].gasConsumption += Number(item.gasConsumption)
  })
  return Object.values(result)
}
function AllMarkerDayGas(data: any[]) {
  const result = {}
  data.forEach((item) => {
    const groupKey = `${item.devNumber}_${item.devNo}` // 使用日期作为分组键
    if (!result[groupKey]) {
      result[groupKey] = {
        sampleTime: '总计',
        devNumber: item.devNumber,
        devNo: item.devNo, // 新增 devNo 字段
        siteName: item.siteName, // 保留站点名称
        devName: item.devName, // 设备名称显示为"总计"
        sumScn: 0,
        sumWcn: 0,
        gasConsumption: 0
      }
    }
    result[groupKey].sumScn += Number(item.sumScn)
    result[groupKey].sumWcn += Number(item.sumWcn)
    result[groupKey].gasConsumption += Number(item.gasConsumption)
  })
  return Object.values(result)
}
export function DayReport() {
  const dataCfg = ref()
  const options = ref()
  const s2 = shallowRef()
  const Date = ref()
  //当点击下载按钮，执行操作
  function ExcelTable() {
    const data = copyData(s2.value?.instance, '\,', true)
    copyToClipboard(data)
    download(data, `${Date.value}月报报表`)
  }
  function PublicFun(Data: MarDayReport[], deviceNo: string) {
    if (deviceNo == 'all') {
      const statistics: any = AllMarkerDayGas(Data)
      Data = statistics.concat(Data)
    } else {
      const statistics: any = DayGasConsumption(Data)
      Data = statistics.concat(Data)
    }
    dataCfg.value = {
      //表格表头内容
      fields: {
        rows: deviceNo == 'all' ? ['siteName', 'devName'] : ['sampleTime'],
        columns: deviceNo == 'all' ? ['sampleTime'] : ['siteName', 'devName'],
        values: ['sumScn', 'sumWcn', 'gasConsumption']
      },
      meta: [
        {
          field: 'sampleTime',
          name: '时间'
        },
        {
          field: 'siteName',
          name: '站点'
        },
        {
          field: 'gasConsumption',
          name: '用气量（m³）'
        },
        {
          field: 'devName',
          name: '流量计'
        },
        {
          field: 'sumScn',
          name: '开始表底'
        },
        {
          field: 'sumWcn',
          name: '结束表底'
        }
      ],
      data: Data
    }
    options.value = {
      height: 400,
      width: 1200,
      showDefaultHeaderActionIcon: false,
      style: {
        cellCfg: {
          width: deviceNo == 'all' ? 100 : 150
        },
        colCfg: {}
      }
    }
  }
  return { dataCfg, options, PublicFun, ExcelTable, Date, s2 }
}
export function MonthReport() {
  const dataCfg = ref()
  const options = ref()
  const Date = ref()
  function PublicFun(Data: MarDayReport[], deviceNo: string) {
    if (deviceNo == 'all') {
      const statistics: any = AllMarkerMonthGas(Data)
      Data = statistics.concat(Data)
    } else {
      const statistics: any = MonthGasConsumption(Data)
      Data = statistics.concat(Data)
    }
    dataCfg.value = {
      //表格表头内容
      fields: {
        rows: deviceNo == 'all' ? ['siteName', 'devName'] : ['date'],
        columns: deviceNo == 'all' ? ['date'] : ['siteName', 'devName'],
        values: ['gasConsumption']
      },
      meta: [
        {
          field: 'date',
          name: '时间'
        },
        {
          field: 'siteName',
          name: '站点'
        },
        {
          field: 'gasConsumption',
          name: '用气量（m³）'
        },
        {
          field: 'devName',
          name: '流量计'
        }
      ],
      data: Data
    }
    options.value = {
      height: 400,
      width: 1200,
      showDefaultHeaderActionIcon: false,
      style: {
        cellCfg: {
          width: deviceNo == 'all' ? 100 : 150
        },
        colCfg: {}
      }
    }
  }
  const s2 = shallowRef()
  //当点击下载按钮，执行操作
  function ExcelTable() {
    const data = copyData(s2.value?.instance, '\,', true)
    copyToClipboard(data)
    download(data, `${Date.value}月报报表`)
  }
  return { dataCfg, options, PublicFun, ExcelTable, Date, s2 }
}
export function Tree() {
  const treeEl = ref<typeof ElTree>() //树结构
  const currentNodeKey = ref<any>() //树结构ID
  const departmentList = ref<any>([]) //树结构数据
  const scadaStore = useSCADAStore()
  const fetchDepartment = async () => {
    const res = ref<MarkerListType[]>([])
    if (scadaStore.getMarkerList.length == 0) {
      res.value = await SCADAApi.GetMarkerList()
      scadaStore.setMarkerList(res.value)
    } else {
      res.value = scadaStore.getMarkerList
    }
    departmentList.value = [
      {
        siteName: '全部站点',
        deviceNo: 'all',
        children: Array.isArray(res.value) ? res.value : []
      }
    ]
    currentNodeKey.value = 'all' //树结构ID也为第一个
    unref(treeEl)?.setCurrentKey(currentNodeKey.value) //应用到树结构};
  }
  return { treeEl, currentNodeKey, departmentList, fetchDepartment }
}
